package com.am.springboot.mybatilspuls.alandolmuseum.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.rmi.ServerException;
import java.util.UUID;

/**
 * @author zewei
 * @create_time 2023/4/6
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload.path}")
    private String path;

    @RequestMapping("/uploaderImg")
    public String uploaderImg(MultipartFile file){
        System.out.println(file);
        if(file == null) return null;
        File pathFile = new File(path);
        if (!pathFile.exists()){
            pathFile.mkdirs();
        }
        String name = file.getOriginalFilename();
        int indexOf = name.indexOf(".");
        String subname = name.substring(indexOf);
        String filename = UUID.randomUUID()+subname;
        try (
                InputStream in = file.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(pathFile,filename));
        ){
            IOUtils.copy(in,out);
        }catch (Exception e){
            e.printStackTrace();
        }
        return filename;
    }


    @RequestMapping("/getImg")
    public void getImg(String fileName, HttpServletResponse response) throws ServerException {
        File file = new File(path,fileName);
        if (!file.exists()){
            throw new ServerException(fileName + "文件不存在");
        }
        try (
                InputStream in = new FileInputStream(file);
                OutputStream out = response.getOutputStream();
        ){
            IOUtils.copy(in,out);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
